import random
import string
import time

from django.shortcuts import render
from django.http import JsonResponse
from .models import User,Book,BorrowRecord
from rest_framework.decorators import api_view
from rest_framework.parsers import JSONParser
from django.db.models import Count,Max,Min,Sum
from django.core.cache import cache
from django.core.signing import Signer
from datetime import timedelta
# Create your views here.

#分页
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
@api_view(['GET'])
def pagedata(request):
    #请求第几页数据
    page=request.GET.get('page')
    #一页显示几条数据
    pagesize=request.GET.get('pagesize')
    #获取表中的所有数据
    alldata=User.objects.filter().values()
    #分页设置
    pageobjall=Paginator(alldata,pagesize)
    try:
        aa=pageobjall.page(page)
    #页码不存在
    except EmptyPage:
        aa=pageobjall.page(pageobjall.num_pages)
    #页码不是一个整型数字
    except PageNotAnInteger:
        aa=pageobjall.page(1)
    #
    #定义一个空列表用于存数用
    lis=[]
    for item in aa.object_list:
        lis.append({
            '用户名':item.get('userme'),
            '密码':item.get('password'),
            '邮箱':item.get('email'),
        })
    return JsonResponse({
        'code':200,
        'msg':'请求成功',
        'data':lis,
        'page':{
            'page':page,
            'pagesize':pagesize,
            'total':alldata.count()
        }
    })


#分页
@api_view(['GET'])
def pagedata(request):
    #请求第几页数据
    page=request.GET.get('page')
    #一页显示几条数据
    pagesize=request.GET.get('pagesize')
    #显示表中所有数据
    alldata=User.objects.filter().values()
    #分页设置
    pageobjall=Paginator(alldata,pagesize)
    try:
        aa=pageobjall.page(page)
    except EmptyPage:
        aa=pageobjall.page(pageobjall.num_pages)
    except PageNotAnInteger:
        aa=pageobjall.page(1)
    lis=[]
    for item in aa.object_list:
        lis.append({
            '名称':item.get('name')
        })
    return JsonResponse({
        'code':200,
        'data':lis,
        'page':{
            'page':page,
            'pagesize':pagesize,
            'total':alldata.count()
        }
    })















#产生token方法
def createtoken(name):
    randomstr=''.join(random.choices(string.ascii_letters,k=8))
    token=Signer().sign(randomstr+name)
    cache.set(f'test_{name}',token,timeout=timedelta(minutes=100).total_seconds())
    return token
def checktoken(request):
    reqtoken=request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False,'xxxx'
    untoken=Signer().unsign(reqtoken)
    name=untoken[8:]
    cachetoken=cache.get(f'test_{name}')
    if cachetoken is None:
        return False,'xxxx'
    return True,name
#登录接口
@api_view(['POST'])
def login(request):
    data=JSONParser().parse(request)
    username=data.get('username')
    password=data.get('password')
    email=data.get('email')
    if User.objects.filter(username=username).exists() is False:
        return JsonResponse({
            'code':401,
            'msg':'用户不存在'
        })
    obj=User.objects.get(username=username)
    if obj.password!=password:
        return JsonResponse({
            'code':404,
            'msg':'密码错误'
        })
    token=createtoken(username)
    return JsonResponse({
        'code': 200,
        'msg': '登录成功',
        'token':token
    })

@api_view(['GET'])
def getbookinfo(request):

    flag,name=checktoken(request)
    if flag is False:
        return JsonResponse({
            'code':400,
            'msg':'未登录,请先登录'
        })

    objs=Book.objects.filter()
    lis=[]
    for obj in objs:
        lis.append({
            'isbn':obj.isbn,
            'bookname':obj.book_name,
            'author':obj.author,
            'puhlishdate':obj.publish_date,
            'stock':obj.stock,
        })
    return JsonResponse({
        'code':200,
        'data':lis,
        'item':objs.count()
    })

@api_view(['PUT'])
def borrowbook(request):
    flag, name = checktoken(request)

    data=JSONParser().parse(request)
    isbn=data.get('isbn')
    if Book.objects.filter(isbn=isbn).exists() is False:
        return JsonResponse({
            'code':401,
            'msg':'书籍不存在'
        })

    obj=Book.objects.get(isbn=isbn)
    if obj.stock==0:
        return JsonResponse({
            'code':400,
            'msg':'库存不足，不能借阅'
        })
    obj.stock=obj.stock-1
    obj.save()
    #获取用户数据对象
    userobj=User.objects.get(username=name)
    #获取当前日期
    data=time.strftime('%Y-%m-%d',time.localtime())
    #保存借阅时间
    BorrowRecord(borrow_date=data,isbn_id=isbn,user_id_id=userobj.id).save()
    return JsonResponse({
        'code':200,
        'msg':'借阅成功'
    })

